package com.gao.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO  操作redis工具类
 * @Author anshenghui
 * @Date 2020/2/11 20:13
 * @Version 1.0
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //取值
    public Object get(String key) {
        return redisTemplate.boundValueOps(key).get();
    }

    //普通存值
    public boolean set(String key, Object value) {
        try {
            redisTemplate.boundValueOps(key).set(value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //批量删除缓存
    public Boolean delete(List<String> key) {
        try {
            redisTemplate.delete(key);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //设置过期时间 单位：秒
    public boolean setExpire(String key, Long time) {
        try {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //获取过期时间 单位：秒
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    //检查redis中某一个key是否存在
    public boolean hasKey(String key) {
       return redisTemplate.hasKey(key);
    }

    //存值并且设置过期时间  单位：秒
    public boolean setCommons(String key, Object value, Long time) {
        boolean set = set(key, value);
        boolean b = setExpire(key, time);
        if (set && b) {
            return true;
        }
        return false;
    }
}
